package com.jxtc.enterprise.admin.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxtc.enterprise.admin.dto.*;
import com.jxtc.enterprise.admin.service.AdminStoreSettleService;
import com.jxtc.enterprise.admin.vo.*;
import com.jxtc.enterprise.common.constants.CompanySettlementStatusEnum;
import com.jxtc.enterprise.common.constants.StoreSettlementStatusEnum;
import com.jxtc.enterprise.common.entity.Store;
import com.jxtc.enterprise.common.entity.StoreSettlement;
import com.jxtc.enterprise.common.exception.ModifyFailureException;
import com.jxtc.enterprise.common.mapper.StoreMapper;
import com.jxtc.enterprise.common.mapper.StoreSettlementMapper;
import com.jxtc.enterprise.common.utils.CurrencyUtil;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.common.vo.PaginationResponseVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/jxtc/enterprise/admin/storeSettle")
@RequiredArgsConstructor
@Slf4j
public class AdminStoreSettlementController {

    private final StoreSettlementMapper storeSettlementMapper;
    private final StoreMapper storeMapper;
    private final AdminStoreSettleService adminStoreSettleService;

    /**
     * 获取店铺结算当前已实现的状态下拉列表，当前已实现了 未结算(10)， 待结算(40),  已结算(50)
     *
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为结算状态字典列表")
    @Operation(summary = "23.1 获取店铺结算当前已实现的状态下拉列表", tags = "23. 管理平台商户结算", operationId = "23.1")
    @GetMapping("/queryStatusListForMerchant")
    public Result<?> queryStatusListForMerchant() {
        // 将结算状态枚举类中的 name - value 转换成列表的形式
        List<Map<String, Object>> settlementStatusList = StoreSettlementStatusEnum.toList();
        return ResultGenerator.genSuccessResult(settlementStatusList);
    }

    /**
     * 根据公司名称，结算账单状态，分页查询账单记录，查询条件过滤规则如下，三个条件是 and 的关系
     * 1. 店铺名称模糊匹配
     * 2. 账单状态 相等才返回
     * 3. 结算账单的 开始时间 或 结束时间 落在查询条件入参时间段内，则返回
     * @param dto
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为包含财务结算列表的分页信息")
    @Operation(summary = "23.2 分页查询店铺财务结算列表", tags = "23. 管理平台店铺结算", operationId = "23.2")
    @PostMapping("/queryStoreSettlementList")
    public Result<PaginationResponseVO<AdminStoreSettlementPageVO>> queryStoreSettlementList(@Valid @RequestBody AdminStoreSettlementPageDTO dto) {
        log.info("/admin/storeSettle/queryStoreSettlementList, storeName: {}, startDate: {}, endDate: {}, status: {}, pageNo: {}, pageSize: {}",
                dto.getStoreName(), dto.getStartDate(), dto.getEndDate(), dto.getStatus(), dto.getPageNo(), dto.getPageSize());

        Page<StoreSettlement> page = new Page<>(dto.getPageNo(), dto.getPageSize());

        LambdaQueryWrapper<StoreSettlement> queryWrapper = new LambdaQueryWrapper<StoreSettlement>()
                // 查询未删除的记录
                .eq(StoreSettlement::getDelFlag, false)
                // 根据 月份、结束时间、开始时间 降序排列
                .orderByDesc(StoreSettlement::getMonth, StoreSettlement::getEndDate, StoreSettlement::getStartDate);

        // 如果店铺名称不空，则拼接 %#{=companyName}%
        if (dto.getStoreName() != null && !dto.getStoreName().isEmpty()) {
            queryWrapper.like(StoreSettlement::getStoreName, dto.getStoreName());
        }

        // 如果开始时间不空，筛选结算开始时间 >= startDate 的记录
        if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
            queryWrapper.ge(StoreSettlement::getStartDate, dto.getStartDate());
        }

        // 如果结束时间不空，筛选结算结束时间 <= endDate 的记录
        if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
            queryWrapper.le(StoreSettlement::getEndDate, dto.getEndDate());
        }

        // 如果结算状态不空且不为 0，筛选结算状态 = status 的记录
        if (dto.getStatus() != null && dto.getStatus() != 0) {
            queryWrapper.eq(StoreSettlement::getStatus, dto.getStatus());
        }

        Page<StoreSettlement> result = storeSettlementMapper.selectPage(page, queryWrapper);
        List<AdminStoreSettlementPageVO> records = result.getRecords().stream()
                .map(adminStoreSettleService::buildStoreSettlementPageVO)
                .collect(Collectors.toList());

        PaginationResponseVO<AdminStoreSettlementPageVO> vo = new PaginationResponseVO<>(result.getTotal(), result.getCurrent(), records);
        log.info("/admin/storeSettle/queryStoreSettlementList, {}", vo);

        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 使用场景
     * 1. 当业务人员新增结算账单时，需要选择时对那个店铺的结算账单，只能通过下来列表挑选，不能手动输入；手动输入存在两个问题，
     *      (1) 容易输入错误，比如拼写错误，导致输入错误的店铺名称; (2) 人为的恶意操作，将账单关联到不相关的店铺
     *
     * 接口功能
     * 1. 获取当前有合作关系店铺列表， store表中，未删除的店铺列表
     *
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为公司及其对应的 ID 的字典列表")
    @Operation(summary = "23.3 查询当前有效的店铺列表", tags = "23. 管理平台公司结算", operationId = "23.3")
    @GetMapping("/queryStoreList")
    public Result<List<?>> queryStoreList() {
        log.info("request /admin/storeSettle/queryStoreList");
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<Store>()
                .eq(Store::getDelFlag, false)
                .orderByDesc(Store::getCreateTime);

        List<Store> storeList = storeMapper.selectList(queryWrapper);
        // 将查询到的店铺列表转换成店铺名称及店铺 ID 的字典列表
        List<Map<String, String>> voList = storeList.stream()
                .map(adminStoreSettleService::buildStoreNameWithId)
                .collect(Collectors.toList());
        log.info("response: {}", voList);
        return ResultGenerator.genSuccessResult(voList);
    }

    /**
     * 接口 23.4 新增商户账单结算记录
     * @param dto
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为空；code 为 400 时，message 字段给出错误提示信息")
    @Operation(summary = "23.4 新增店铺结算记录", tags = "23. 管理平台公司结算", operationId = "23.4")
    @PostMapping("/addStoreSettlementRecord")
    public Result<Void> addStoreSettlementRecord(@Valid @RequestBody AddStoreSettlementRecordDTO dto) {
        log.info("request /admin/storeSettle/addStoreSettlementRecord, request body: {}", dto);

        Store store = storeMapper.selectById(dto.getStoreId());
        if (store == null) {
            throw new IllegalArgumentException("ID 为 " + dto.getStoreId() + " 的店铺不存在，请联系管理员排查");
        }

        StoreSettlement storeSettlement = new StoreSettlement();
        storeSettlement.setStoreId(dto.getStoreId());
        storeSettlement.setStoreName(dto.getStoreName());
        storeSettlement.setMonth(dto.getMonth());
        storeSettlement.setStartDate(dto.getStartDate());
        storeSettlement.setEndDate(dto.getEndDate());
        storeSettlement.setNoteDay(dto.getNoteDay());

        // TODO: 查询并更新订单数据
        storeSettlement.setTotalOrderCount(20000);
        storeSettlement.setOrderMoney(20000);

        // TODO: 生成订单详情文件，并上传到阿里云 oss 对象存储中
        String billUrl = "";
        storeSettlement.setBillUrl(billUrl);

        // 向数据库添加数据，添加失败时给前端提供提示信息
        int insertCount = storeSettlementMapper.insert(storeSettlement);
        log.info("/admin/storeSettle/addStoreSettlementRecord, insert count: {}", insertCount);

        if (insertCount <= 0) {
            throw new ModifyFailureException("新增结算记录失败，请联系管理员排查");
        }
        log.info("response /admin/storeSettle/addStoreSettlementRecord success");
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 接口23.5 查询某个店铺结算账单基本信息
     *
     * @param settleId
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为结算记录基本信息；code 为 400 时，message 字段给出错误提示信息")
    @Parameter(name = "settleId", description = "店铺结算记录 ID", example = "26e7c8b17867fa08584f92e1638b8eba")
    @Operation(summary = "23.5 查询店铺结算记录基本信息", tags = "23. 管理平台公司结算", operationId = "23.5")
    @GetMapping("/queryStoreSettlementBasicInfo")
    public Result<BasicStoreSettlementInfoVO> queryStoreSettlementBasicInfo(@RequestParam String settleId) {
        log.info("/admin/storeSettle/queryStoreSettlementBasicInfo, settleId: {}", settleId);
        StoreSettlement storeSettlement = storeSettlementMapper.selectById(settleId);
        if (storeSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + settleId + " 的结算记录不存在，请联系管理员排查");
        }

        BasicStoreSettlementInfoVO vo = new BasicStoreSettlementInfoVO();
        vo.setSettleId(storeSettlement.getId());
        vo.setStoreId(storeSettlement.getStoreId());
        vo.setStoreName(storeSettlement.getStoreName());
        vo.setMonth(storeSettlement.getMonth());
        vo.setStartDate(storeSettlement.getStartDate());
        vo.setEndDate(storeSettlement.getEndDate());
        vo.setNoteDay(storeSettlement.getNoteDay());
        log.info("/admin/storeSettle/queryStoreSettlementBasicInfo, response: {}", vo);
        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 接口23.6 编辑店铺结算账单基本信息
     *
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为结算记录基本信息；code 为 400 时，message 字段给出错误提示信息")
    @Parameter(name = "settleId", description = "店铺结算记录 ID", example = "26e7c8b17867fa08584f92e1638b8eba")
    @Operation(summary = "23.6 编辑店铺结算记录基本信息", tags = "23. 管理平台店铺结算", operationId = "23.6")
    @PostMapping("/editStoreSettlementBasicInfo")
    public Result<BasicStoreSettlementInfoVO> editStoreSettlementBasicInfo(@Valid @RequestBody EditStoreSettlementRecordDTO dto) {
        log.info("/admin/editCompanySettlementRecord, settleId: {}, month: {}, startDate: {}, endDate: {}, noteDay: {}",
                dto.getSettleId(), dto.getMonth(), dto.getStartDate(), dto.getEndDate(), dto.getNoteDay());

        StoreSettlement savedStoreSettlement = storeSettlementMapper.selectById(dto.getSettleId());
        if (savedStoreSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + dto.getSettleId() + " 的结算记录不存在，请联系管理员排查");
        }

        // 如果当前结算记录的状态为 "已结算"，则不允许编辑
        if (StoreSettlementStatusEnum.SETTLED.getValue() == savedStoreSettlement.getStatus()) {
            throw new ModifyFailureException("ID 为 " + dto.getSettleId() + " 的结算记录不允许编辑");
        }

        StoreSettlement updateStoreSettlement = new StoreSettlement();
        updateStoreSettlement.setId(dto.getSettleId());

        String month = savedStoreSettlement.getMonth();
        if (dto.getMonth() != null && !dto.getMonth().isEmpty()) {
            month = dto.getMonth();
            updateStoreSettlement.setMonth(dto.getMonth());
        }

        String startDate = savedStoreSettlement.getStartDate();
        if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
            startDate = dto.getStartDate();
            updateStoreSettlement.setStartDate(dto.getStartDate());
        }

        String endDate = savedStoreSettlement.getEndDate();
        if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
            endDate = dto.getEndDate();
            updateStoreSettlement.setEndDate(dto.getEndDate());
        }

        Integer noteDay = savedStoreSettlement.getNoteDay();
        if (dto.getNoteDay() != null) {
            noteDay = dto.getNoteDay();
            updateStoreSettlement.setNoteDay(dto.getNoteDay());
        }

        // 判断是否修改了结算周期（即：是否修改了 "结算开始时间" 或 "结算结束时间"）
        // 如果修改了结算周期，那么订单的总份数、总金额、以及订单详情文件都需要重新计算和生成，然后上传到 OSS 服务
        // 否则，直接修改数据库中记录即可
        boolean hasEditedDate = (dto.getStartDate() != null && !dto.getStartDate().isEmpty())
                || (dto.getEndDate() != null && !dto.getEndDate().isEmpty());
        log.info("/admin/editCompanySettlementRecord, hasEditedDate：{}", hasEditedDate);

        if (hasEditedDate) {
            log.info("/admin/editCompanySettlementRecord, 更新了结束时间范围，重新计算订单相关数据");
            updateStoreSettlement = adminStoreSettleService.buildStoreSettlement(savedStoreSettlement.getStoreId(), month, startDate, endDate, noteDay);
            updateStoreSettlement.setId(dto.getSettleId());
            log.info("/admin/editCompanySettlementRecord, 重新计算后的结算记录: {}", updateStoreSettlement);
        }

        // 向数据库更新数据，更新失败时给前端提供提示信息
        int updateCount = storeSettlementMapper.updateById(updateStoreSettlement);
        log.info("/admin/editCompanySettlementRecord, update count: {}", updateCount);

        if (updateCount <= 0) {
            throw new ModifyFailureException("更新失败，请稍后重试");
        }

        return ResultGenerator.genSuccessResult();
    }


    /**
     * 删除某个店铺账单结算记录，只能删除状态不是 “已结算” 的账单
     * @param settleId
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示删除结算记录成功，data 字段为空；code 为 400 时，message 字段给出错误提示信息")
    @Parameter(name = "settleId", description = "公司结算记录 ID", example = "26e7c8b17867fa08584f92e1638b8eba")
    @Operation(summary = "23.7 删除店铺结算记录", tags = "23. 管理平台店铺结算", operationId = "23.7")
    @GetMapping("/deleteStoreSettlement")
    public Result<Void> deleteStoreSettlement(@RequestParam String settleId) {
        log.info("/admin/storeSettle/deleteStoreSettlement, settleId: {}", settleId);

        StoreSettlement storeSettlement = storeSettlementMapper.selectById(settleId);
        if (storeSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + settleId + " 的结算记录不存在，请联系管理员排查");
        }

        // 如果当前结算记录的状态为 "已结算"，则不允许删除
        if (StoreSettlementStatusEnum.SETTLED.getValue() == storeSettlement.getStatus()) {
            throw new ModifyFailureException("ID 为 " + settleId + " 的结算记录不允许删除");
        }

        StoreSettlement updateStoreSettlement = new StoreSettlement();
        updateStoreSettlement.setId(settleId);
        updateStoreSettlement.setDelFlag(true);

        int updateCount = storeSettlementMapper.updateById(updateStoreSettlement);
        log.info("/admin/storeSettle/deleteStoreSettlement, update count: {}", updateCount);

        if (updateCount <= 0) {
            throw new ModifyFailureException("ID 为 " + settleId + " 的结算记录删除失败，请联系管理员排查");
        }

        return ResultGenerator.genSuccessResult();
    }


    /**
     * 功能：查看结算账单详情，包括总订单份数，订单金额，附加款项，扣款项，业务人员填写的备注，上传的 发票，转账凭证
     * 使用场景
     * 1. 查看历史结算账单详情，比如 9月时查看3月已结算的账单详情
     * 2. 流程中的账单，查看账单信息，备注描述等
     *
     * @param settleId
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为结算详情信息；code 为 400 时，message 字段给出错误提示信息")
    @Parameter(name = "settleId", description = "公司结算记录 ID", example = "26e7c8b17867fa08584f92e1638b8eba")
    @Operation(summary = "23.8 查询结算详情", tags = "23. 管理平台公司结算", operationId = "23.8")
    @GetMapping("/queryStoreSettlementDetails")
    public Result<AdminStoreSettlementDetailVO> queryStoreSettlementDetails(@RequestParam String settleId) {
        log.info("/admin/storeSettle/queryStoreSettlementDetails, settleId: {}", settleId);

        LambdaQueryWrapper<StoreSettlement> queryWrapper = new LambdaQueryWrapper<StoreSettlement>()
                .eq(StoreSettlement::getId, settleId)
                .eq(StoreSettlement::getDelFlag, false);

        StoreSettlement storeSettlement = storeSettlementMapper.selectOne(queryWrapper);

        if (storeSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + settleId + " 的结算记录不存在，请联系管理员排查");
        }

        AdminStoreSettlementDetailVO vo = new AdminStoreSettlementDetailVO();
        vo.setSettleId(settleId);

        String billPeriod = String.format("%s ~ %s", storeSettlement.getStartDate(), storeSettlement.getEndDate());
        vo.setBillPeriod(billPeriod);
        vo.setTotalOrderCount(storeSettlement.getTotalOrderCount());

        String orderMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getOrderMoney());
        vo.setOrderMoney(orderMoneyInYuan);

        String additionalMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getAdditionalMoney());
        vo.setAdditionalMoney(additionalMoneyInYuan);

        String deductionMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getDeductionMoney());
        vo.setDeductionMoney(deductionMoneyInYuan);
        // 扣款项取绝对值，避免页面输入的时候输入了负数
        int billTotalMoneyInFen = storeSettlement.getOrderMoney() + storeSettlement.getAdditionalMoney() - Math.abs(storeSettlement.getDeductionMoney());
        String billTotalMoneyInYuan = CurrencyUtil.fenToYuan(billTotalMoneyInFen);
        vo.setBillTotalMoney(billTotalMoneyInYuan);

        List<String> invoiceImages = JSONUtil.toList(storeSettlement.getInvoiceImages(), String.class);
        vo.setInvoiceImages(invoiceImages);

        List<String> transferImages = JSONUtil.toList(storeSettlement.getTransferImages(), String.class);
        vo.setTransferImages(transferImages);

        List<AdminBillLogVO> billLogs = JSONUtil.toList(storeSettlement.getBillLog(), AdminBillLogVO.class);
        vo.setBillLogs(billLogs);

        Integer statusValue = storeSettlement.getStatus();
        vo.setStatusName(CompanySettlementStatusEnum.getNameByValue(statusValue));
        vo.setStatusValue(statusValue);

        log.info("/admin/storeSettle/queryStoreSettlementDetails, response: {}", vo);

        return ResultGenerator.genSuccessResult(vo);
    }


    /**
     * 接口23.9 业务人员发起结算流程，之后商户小程序上就可以看到 账单信息
     * 使用场景
     * 1. 业务人员发起结算，填写附加款项，扣款项后，点击【提交】按钮 后调用此接口
     *
     * @param dto
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示提交结算订单成功，data 字段为空；code 为 400 时，message 字段给出错误提示信息")
    @Operation(summary = "23.9 提交结算订单", tags = "23. 管理平台公司结算", operationId = "23.9")
    @PostMapping("/submitCompanySettlement")
    public Result<Void> submitCompanySettlement(@Valid @RequestBody SubmitCompanySettlementDTO dto) {
        log.info("/admin/storeSettle/submitCompanySettlement, request: {}",dto);

        StoreSettlement savedStoreSettlement = storeSettlementMapper.selectById(dto.getSettleId());
        if (savedStoreSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + dto.getSettleId() + " 的结算记录不存在，请联系管理员排查");
        }

        StoreSettlement storeSettlement = new StoreSettlement();
        storeSettlement.setId(savedStoreSettlement.getId());

        if (dto.getAdditionalMoney() != null && !dto.getAdditionalMoney().isEmpty()) {
            BigDecimal additionalMoneyInYuan = new BigDecimal(dto.getAdditionalMoney());
            int additionalMoneyInFen = CurrencyUtil.yuanToFen(additionalMoneyInYuan);
            storeSettlement.setAdditionalMoney(additionalMoneyInFen);
        }

        if (dto.getDeductionMoney() != null && !dto.getDeductionMoney().isEmpty()) {
            BigDecimal deductionMoneyInYuan = new BigDecimal(dto.getDeductionMoney());
            int deductionMoneyInFen = CurrencyUtil.yuanToFen(deductionMoneyInYuan);
            storeSettlement.setDeductionMoney(deductionMoneyInFen);
        }

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String comment = "业务人员发起结算";
        if (dto.getComment() != null && !dto.getComment().isEmpty()) {
            comment += "，备注：" + dto.getComment();
        }

        List<AdminBillLogVO> billLogs = JSONUtil.toList(savedStoreSettlement.getBillLog(), AdminBillLogVO.class);
        AdminBillLogVO adminBillLogVO = new AdminBillLogVO(now.format(formatter), comment);
        billLogs.add(adminBillLogVO);

        String billLogStr = JSONUtil.toJsonStr(billLogs);
        storeSettlement.setBillLog(billLogStr);

        // 将结算状态设置为 "待 HR 确认"
        storeSettlement.setStatus(StoreSettlementStatusEnum.PENDING_SETTLEMENT.getValue());

        int updateCount = storeSettlementMapper.updateById(storeSettlement);
        log.info("/admin/storeSettle/submitCompanySettlement, update count: {}", updateCount);

        if (updateCount <= 0) {
            throw new ModifyFailureException("提交结算订单失败，请联系管理员排查");
        }

        return ResultGenerator.genSuccessResult();
    }


    /**
     * 接口 23.10 线下与商户确认账单，转账后，在系统中上传图片，补充账单转账相关的凭证图片
     *
     * @param dto
     * @return
     */
    @ApiResponse(responseCode = "200", description = "code 为 200 时，表示补全结算附件成功，data 字段为空；code 为 400 时，message 字段给出错误提示信息")
    @Operation(summary = "23.10 补全店铺结算附件", tags = "23. 管理平台店铺结算", operationId = "23.10")
    @PostMapping("/complementStoreSettlement")
    public Result<Void> complementStoreSettlement(@Valid @RequestBody ComplementCompanySettlementDTO dto) {
        log.info("/admin/storeSettle/complementStoreSettlement, request: {}", dto);

        if (dto.getInvoiceImages() != null && dto.getInvoiceImages().size() > 5) {
            throw new IllegalArgumentException("发票凭证图片最多 5 张");
        }

        if (dto.getTransferImages() != null && dto.getTransferImages().size() > 5) {
            throw new IllegalArgumentException("转账凭证图片最多 5 张");
        }

        StoreSettlement savedStoreSettlement = storeSettlementMapper.selectById(dto.getSettleId());
        if (savedStoreSettlement == null) {
            throw new IllegalArgumentException("ID 为 " + dto.getSettleId() + " 的结算记录不存在，请联系管理员排查");
        }

        StoreSettlement storeSettlement = new StoreSettlement();
        storeSettlement.setId(savedStoreSettlement.getId());

        if (dto.getInvoiceImages() != null) {
            String invoiceImageStr = JSONUtil.toJsonStr(dto.getInvoiceImages());
            storeSettlement.setInvoiceImages(invoiceImageStr);
        }

        if (dto.getTransferImages() != null) {
            String transferImageStr = JSONUtil.toJsonStr(dto.getTransferImages());
            storeSettlement.setTransferImages(transferImageStr);
        }

        // 将备注和当前时间追加到结算流程日志中
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String comment = "业务人员上传凭证";
        if (dto.getComment() != null && !dto.getComment().isEmpty()) {
            comment += "，备注：" + dto.getComment();
        }
        AdminBillLogVO adminBillLogVO = new AdminBillLogVO(now.format(formatter), comment);
        List<AdminBillLogVO> billLogs = JSONUtil.toList(savedStoreSettlement.getBillLog(), AdminBillLogVO.class);
        billLogs.add(adminBillLogVO);
        String billLogStr = JSONUtil.toJsonStr(billLogs);
        storeSettlement.setBillLog(billLogStr);

        // 将结算状态设置为 "已结算"
        storeSettlement.setStatus(CompanySettlementStatusEnum.SETTLED.getValue());

        int updateCount = storeSettlementMapper.updateById(storeSettlement);
        log.info("/admin/storeSettle/complementStoreSettlement, update count: {}", updateCount);

        if (updateCount <= 0) {
            throw new ModifyFailureException("补全结算附件失败，请联系管理员排查");
        }

        return ResultGenerator.genSuccessResult();
    }

}
